<?php

namespace services\patient;

use common\helpers\CommonHelper;
use common\models\patient\OperateLog;
use Yii;
use common\models\base\User;
use common\components\Service;
use common\models\patient\Tags;
use common\models\marketing\Tags as MarketingTags;
use common\models\patient\User as PatientUser;
use yii\web\HttpException;

/**
 * Class TagsService
 * @package services\patient
 */
class TagsService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return Tags|null
     */
    public function findById(int $id = 0): ?Tags
    {
        return Tags::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return Tags|null
     */
    public function findInfo(array $condition = []): ?Tags
    {
        $query = Tags::find();

        isset($condition['patient_user_id']) && $query->andWhere(['patient_user_id' => $condition['patient_user_id']]);
        isset($condition['tags_id']) && $query->andWhere(['tags_id' => $condition['tags_id']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Tags::find();

        isset($condition['patient_user_id']) && $query->andWhere(['patient_user_id' => $condition['patient_user_id']]);
        isset($condition['tags_id']) && $query->andWhere(['tags_id' => $condition['tags_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 更新患者标签
     *
     * @param array $params
     * @return int
     * @throws \yii\db\Exception
     * @author chenyuebin
     */
    public function tagsEdit(array $params)
    {
        $tagsArr = array_unique(array_filter(explode(',', $params['tags_id'])));
        // 表去标签名称
        $tagsStr = '';
        if (count($tagsArr) > 0) {
            $tagsList = MarketingTags::find()
                ->select('tags_name')
                ->where(['in', 'id', $tagsArr])
                ->asArray()
                ->all();

            foreach ($tagsList as $value) {
                $tagsStr .= $value['tags_name'] . ',';
            }
        }
        $oldTags = PatientUser::find()->select('patient_tags_name')->where(['id' => $params['patient_user_id']])->scalar();

        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 设置患者标签表对应患者当前标签为删除
            Tags::updateAll(['status' => Tags::STATUS_DELETE], ['patient_user_id' => $params['patient_user_id']]);

            // 修改患者表标签冗余字段
            PatientUser::updateAll(['patient_tags_name' => trim($tagsStr, ',')], ['id' => $params['patient_user_id']]);
            // 修改患者标签表
            $data = [];
            foreach ($tagsArr as $key => $value) {
                $data[$key]['tags_id'] = $value;
                $data[$key]['patient_user_id'] = $params['patient_user_id'];
                $data[$key]['created_at'] = time();
                $data[$key]['updated_at'] = time();
            }
            if ($data){
                if (!Yii::$app->db->createCommand()->batchInsert(Tags::tableName(), ['tags_id', 'patient_user_id', 'created_at', 'updated_at'], $data)->execute()) {
                    throw new HttpException(422, '标签更新失败');
                }
            }

            $operateLog = new OperateLog();
            $operateLog->project_id = $params['project_id'];
            $operateLog->patient_user_id = $params['patient_user_id'];
            $operateLog->action_type = OperateLog::ACTION_TYPE_PATIENT_UPDATE;
            $operateLog->action_content = "患者标签由【{$oldTags}】变更为【" . trim($tagsStr, ',') . "】;";
            $operateLog->operate_name = Yii::$app->user->identity->member->realname;
            $operateLog->operate_id = Yii::$app->user->identity->member_id;
            if (!$operateLog->save()) {
                throw new HttpException(422, '日志表更新失败');
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }
        return true;
    }

}